﻿#pragma once

#include "lp_conf.h"

#ifdef LP_WINDOWS
#include <Windows.h>
#else
    #define _XOPEN_SOURCE 500
    #include <pthread.h>
    #include <unistd.h>

     #ifndef pthread_spinlock_t
         #define pthread_spinlock_t      pthread_mutex_t
         #define pthread_spin_init(l, v)    pthread_mutex_init(l, NULL)
         #define pthread_spin_lock(l)    pthread_mutex_lock(l)
         #define pthread_spin_trylock(l) pthread_mutex_trylock(l)
         #define pthread_spin_unlock(l)  pthread_mutex_unlock(l)
         #define pthread_spin_destroy(l) pthread_mutex_destroy(l)
     #endif
#endif



#ifdef LP_WINDOWS
typedef DWORD LPThread;
#else
typedef pthread_t LPThread;
#endif


typedef struct{
#ifdef LP_WINDOWS
    BOOL lock;
#else
    pthread_spinlock_t  lock;
#endif
}LPSpinLock;

typedef struct{
#ifdef LP_WINDOWS
    CRITICAL_SECTION lock;
#else
    pthread_mutex_t lock;
#endif
}LPMutex;

typedef struct {
#ifdef LP_WINDOWS
    SRWLOCK lock;
#else
    pthread_rwlock_t lock;
#endif
}LPRWLock;

typedef struct {
#ifdef LP_WINDOWS
	// HAND evt;
    CONDITION_VARIABLE cond;
    CRITICAL_SECTION lock;
#else
    pthread_mutex_t lock;
    pthread_cond_t cond;
#endif
}LPCond;

LP_API int
lpNewThread (LPThread * t,
	void *(*start_fn)(void *), void * arg, int detach);

LP_API void
lpExitThread ();

LP_API int
lpCancelthread (LPThread t);

LP_API int
lpJoinThread (LPThread t);

LP_API LPThread
lpSelfThread ();

LP_API void
lpSleepms (uint32_t ms);


LP_API void
lpInitSpin(LPSpinLock * l);

LP_API void
lpClearSpin(LPSpinLock * l);

LP_API int
lpLockSpin(LPSpinLock * l);

LP_API int
lpTryLockSpin(LPSpinLock * l);

LP_API int
lpUnlockSpin(LPSpinLock * l);


LP_API void
lpInitMutex(LPMutex * l);

LP_API int
lpLockMutex(LPMutex * l);

LP_API int
lpTryLockMutex(LPMutex * l);

LP_API int
lpUnlockMutex(LPMutex * l);

LP_API void
lpClearMutex(LPMutex * l);


LP_API void
lpInitRWLock (LPRWLock * l);

LP_API void
lpClearRWLock(LPRWLock * l);

LP_API void
lpLockRWLockR (LPRWLock * l);

LP_API void
lpLockRWLockW (LPRWLock * l);

LP_API void
lpUnlockRWLockR (LPRWLock * l);

LP_API void
lpUnlockRWLockW (LPRWLock * l);


LP_API void
lpInitCond (LPCond * cond);

LP_API void
lpClearCond (LPCond * cond);

LP_API int
lpLockCond (LPCond * cond);

LP_API int
lpTryLockCond (LPCond * cond);

LP_API int
lpUnlockCond (LPCond * cond);

LP_API int
lpWaitCond (LPCond * cond);

LP_API int
lpWaitCondTimeout (LPCond * cond, uint32_t ms);

LP_API int
lpSignalCond (LPCond * cond);

LP_API int
lpBroadcastCond (LPCond * cond);

